import axios from 'axios'
import store from '@/store'
import { Toast, Dialog } from 'vant'
import router from '@/router'

// 根据环境不同引入不同api地址
import { baseUrl, baseApi } from '@/config'
// create an axios instance
const service = axios.create({
  baseURL: baseUrl + baseApi, // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        duration: 0,
        forbidClick: true
      })
    }
    if (store.state.user) {
      config.headers['Authorization'] = `${store.state.user.token}`;
    }
    config.headers['hideloading'] = config.hideloading;
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(

  response => {

    if(!response.config.headers.hideloading){
      Toast.clear()
    }
    // Toast.clear()
    const res = response.data;

    if (res.code && res.code !== 0) {
      // 登录超时,重新登录
      if (res.code === -1) {
        store.dispatch('logout');
        // 登录失效
        router.push({
          path: '/login/1'
        })
      }else{
        Dialog({ 
          title: '提示',
          message: res.msg || `请求异常（未知出错${res.code}）！` 
        })
      }
      return Promise.reject(res || 'error')
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    if(error){
      debugger;
      Dialog({ 
        title: '提示',
        message: error.msg || `请求异常（${error.message || '未知'}）！` 
      })
    }
    return Promise.reject(error)
  }
)

export default service
